package com.example.demo.bizhan.thread;

import lombok.Data;

/**
 * @description: wait notifyAll必须在synchronized里面调用
 * @time: 2020-10-28 21:27
 * @author: baojinlong
 **/
@Data
public class Person {
    private String name;
    private String sex;
    private boolean isEmpty = true;

    // 加synchronized可以解决
    public synchronized void set(String name, String sex) {
        // 不为空,生产者应该停下来,等到消费者去消费
        while (!isEmpty) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        this.name = name;
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        this.sex = sex;
        System.out.println("生产: " + getName() + " : " + getSex());
        // 将标志为重置
        isEmpty = false;
        // 唤醒消费者,起来消费了
        this.notifyAll();
    }

    // 加synchronized可以解决
    public synchronized void get() {
        // 如果为空的时候
        while (isEmpty) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("消费: " + getName() + " : " + getSex());
        isEmpty = true;
        // 唤醒生产者
        this.notifyAll();
    }
}
